//
//  YWPhototBrowserController.m
//  Chinese
//
//  Created by yellow on 2021/3/8.
//  Copyright © 2021 YSLC. All rights reserved.
//

#import "YWPhototBrowserController.h"
#import "YWPhotoBrowserCollectionViewLayout.h"
#import "UIButton+YWPhotoBrowserBtn.h"
#import "YWPhotoBrowserCell.h"
#import "YWPhotoBrowserAnimator.h"


@interface YWPhototBrowserController ()<UICollectionViewDataSource,YWPhotoBrowserCellDelegate,YWPhotoBrowserAnimatorDismissDelegate>

@property(nonatomic,strong)UICollectionView *collectionView;
@property(nonatomic,strong)UIButton *closeBtn;
@property(nonatomic,strong)UIButton *saveBtn;

@end

@implementation YWPhototBrowserController

static NSString * const cellID = @"YWPhotoBrowserCell";

-(UIButton *)closeBtn{
    if (_closeBtn == nil) {
        _closeBtn = [UIButton buttonWithBgColor:YWColor(50, 50, 50) fontSize:14 title:@"关 闭"];
        
        [_closeBtn addTarget:self action:@selector(closeBtnClick) forControlEvents:UIControlEventTouchUpInside];
        
        
    }
    return _closeBtn;
}
-(UIButton *)saveBtn{
    if (_saveBtn == nil) {
        _saveBtn = [UIButton buttonWithBgColor:YWColor(50, 50, 50) fontSize:15 title:@"保 存"];
        
        [_saveBtn addTarget:self action:@selector(saveBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _saveBtn;
}

-(UICollectionView *)collectionView{
    if (_collectionView == nil) {
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:[[YWPhotoBrowserCollectionViewLayout alloc]init]];
        
        [_collectionView registerClass:[YWPhotoBrowserCell class] forCellWithReuseIdentifier:cellID];
        
        _collectionView.dataSource = self;
        
        _collectionView.backgroundColor = [UIColor clearColor];
        
    }
    return _collectionView;
}


-(instancetype)initWithImgBeginIndexPath:(NSIndexPath *)indexPath picUrlArray:(NSArray <NSString *>*)picUrlArray{
    
    self = [super init];
    if (self) {
        self.indexPath = indexPath;
        self.picUrlArray = picUrlArray;
    }
    return self;
    
}

-(void)loadView{
    [super loadView];
    
    self.view.width += 20;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    // 1.设置UI界面
    [self setupUI];
    
    // 2.滚动到对应的图片
    [self.collectionView scrollToItemAtIndexPath:self.indexPath atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
    
    
    self.view.backgroundColor = [UIColor blackColor];
    self.navBar.alpha = 0;
    
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(pan:)];
    
    [self.view addGestureRecognizer:pan];
    
}

-(void)pan:(UIPanGestureRecognizer *)pan{
 
    CGPoint transP = [pan translationInView:self.view];
    
    switch (pan.state) {
        case UIGestureRecognizerStateBegan:
        {
            self.saveBtn.hidden = YES;
            self.closeBtn.hidden = YES;
        }
            break;
        case UIGestureRecognizerStateChanged:
        {
            //事实证明、transform会改变frame值、所以这里是frame和transform共同配合完成、基本上是transform来做改值、frame来做条件判断
            
            
            //不能改变frame、因为内部控件没用autolayout，不会跟着变小、所以这里注释了
//            改变collectionView位置
//            self.collectionView.x = self.collectionView.x + transP.x;
//            self.collectionView.y = self.collectionView.y + transP.y;
//            
////            改变self.view的backgroundColor的透明度
////            self.view.backgroundColor的alpha最大值是1 移动越远越接近0、1-比例
            CGFloat alpha = 1 - self.collectionView.y/He;
            self.view.backgroundColor = YWColorRGBA(0, 0, 0, alpha);
            
           //这里不要用绝对值、所以注释了
//            改变collectionView大小
//            比例正常是1、就是最大值是1
//            CGFloat ratio = 1 - fabs(self.collectionView.y)/He;
//            self.collectionView.width = self.view.width * ratio;
//            self.collectionView.height = self.view.height *ratio;
            
            
            self.collectionView.transform = CGAffineTransformTranslate(self.collectionView.transform, transP.x, transP.y);
            
            //因为缩放和移动的transform，所以只能用CGAffineTransformTranslate和CGAffineTransformScale
            
            //因为CGAffineTransformMakeTranslation是一次性改变的、所以注释了
//            self.collectionView.transform = CGAffineTransformMakeTranslation(self.collectionView.x + transP.x, self.collectionView.y + transP.y);
            
            //移动距离越大、除以固定He的分母后值就越大、再拿1减就值就越小（即scaleRati越小）、所以移动距离越大、缩小得越厉害
            CGFloat scaleRati = 1- transP.y/He;
            
          

            YWLog(@"%f",scaleRati);
            
            //它这个transP是从开始移动到停止移动会变化一次、然后又清零、而x、y是累积变化
            YWLog(@"transP:%@,x:%f,y:%f",NSStringFromCGPoint(transP),self.collectionView.x,self.collectionView.y);
            
            //当collectionView.y大于等于0时，大小才发生变化
            if (self.collectionView.y>=0) {
                self.collectionView.transform = CGAffineTransformScale(self.collectionView.transform, scaleRati, scaleRati);
            }
            
            
           //不需要anchorPoint、默认就是0.5 0.5
//            self.collectionView.layer.anchorPoint = CGPointMake(0.5, 0.5);
          //因为CGAffineTransformMakeScale是一次性改变的、所以注释了
//            self.collectionView.transform = CGAffineTransformMakeScale(scaleRati, scaleRati);
            
//            YWLog(@"%@",NSStringFromCGRect(self.collectionView.frame));
            
        }
            break;
        case UIGestureRecognizerStateEnded:
        {
            if (self.collectionView.y>He/3.0) {
                [self dismissViewControllerAnimated:YES completion:nil];
            }
            else{
                [UIView animateWithDuration:0.3 animations:^{
                    
                    self.collectionView.transform = CGAffineTransformIdentity;
                    
                    self.view.backgroundColor = YWColorRGBA(0, 0, 0, 1);
                    
                }completion:^(BOOL finished) {
                    
                        self.saveBtn.hidden = NO;
                        self.closeBtn.hidden = NO;
                }];
            }
            
           
        }
            break;
            
        default:
            break;
    }
    
//    YWLog(@"%@",NSStringFromCGPoint(transP));
    
    
    //复位.
    [pan setTranslation:CGPointZero inView:self.view];
    
}



-(void)setupUI{
    
        // 1.添加子控件
    [self.view addSubview:self.collectionView];
    [self.view addSubview:self.closeBtn];
    [self.view addSubview:self.saveBtn];
    
    // 2.设置frame
    self.collectionView.frame = self.view.bounds;
    
    MJWeakSelf
    [self.closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.view).offset(20);
        make.bottom.equalTo(weakSelf.view).offset(-20);
        make.height.equalTo(@32);
        make.width.equalTo(@90);
    }];
    
    [self.saveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(weakSelf.view).offset(-40);
        make.bottom.equalTo(weakSelf.closeBtn.mas_bottom);
        make.height.equalTo(weakSelf.closeBtn.mas_height);
        make.width.equalTo(weakSelf.closeBtn.mas_width);
    }];
    
}

-(void)closeBtnClick{
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)saveBtnClick{
    YWPhotoBrowserCell *cell = (YWPhotoBrowserCell *)(self.collectionView.visibleCells.firstObject);
    UIImage *image = cell.imageView.image;
    if (image == nil) {
        return;
    }
    
    
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    
    
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    
    if (error != nil) {
        [MBProgressHUD showError:@"保存失败" toView:self.view];
    }
    else{
        [MBProgressHUD showSuccess:@"保存成功" toView:self.view];
    }
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.picUrlArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath{
    
    // 1.创建cell
    YWPhotoBrowserCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
    
    // 2.给cell设置数据
    NSString *urlString = self.picUrlArray[indexPath.item];
    
    //因为这里没有大图小图之分、所以统一用一张图
    [cell setupImgWithLittleUrlString:urlString bigUrlString:urlString];
    
    cell.delegate = self;
    
    return cell;
    
}

-(void)photoBrowserCell:(YWPhotoBrowserCell *)photoBrowserCell didTapWithUrl:(nonnull NSString *)urlString{
    
    [self closeBtnClick];
}

#pragma mark - AnimatorDismissDelegate
-(NSIndexPath *)indexPathForDismissView{
    
    // 1.获取当前正在显示的indexPath
    YWPhotoBrowserCell *cell = self.collectionView.visibleCells.firstObject;
    
    NSIndexPath *imgEndIndexPath = [self.collectionView indexPathForCell:cell];
    
    return imgEndIndexPath;
}

//这个代理返回的imageView既有frame也有image
-(UIImageView *)imageViewForDimissView{
    
    // 1.创建UIImageView对象
    UIImageView *imageView = [[UIImageView alloc] init];
    
    // 2.设置imageView的frame
    YWPhotoBrowserCell *cell = self.collectionView.visibleCells.firstObject;
    
    //转化为相对于window的frame
    CGRect imageRectForWindow = [cell.scrollView convertRect:cell.imageView.frame toView:[UIApplication sharedApplication].keyWindow];
    
    imageView.frame = imageRectForWindow;
    imageView.image = cell.imageView.image;
    
    // 3.设置imageView的属性
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.clipsToBounds = YES;
    
    return imageView;
}


@end
